package com.xls.commonlibrary.ad.adn.gm;

import static com.xls.commonlibrary.constant.Const.HYLC_XXL_BN_TEST;
import static com.xls.commonlibrary.constant.Const.HYLC_XXL_BN_TEST_INDEX;
import static com.xls.commonlibrary.constant.Const.HYLC_XXL_INFOSTREAM_TEST;
import static com.xls.commonlibrary.constant.Const.HYLC_XXL_INFOSTREAM_TEST_INDEX;

import android.util.Log;
import android.view.View;
import android.webkit.ValueCallback;
import android.widget.FrameLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTFeedAd;
import com.bytedance.sdk.openadsdk.TTNativeAd;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationExpressRenderListener;
import com.bytedance.sdk.openadsdk.mediation.manager.MediationNativeManager;
import com.xls.commonlibrary.http.biz.CodeRewardUtil;

import java.util.List;

import io.reactivex.rxjava3.annotations.NonNull;

public class GMFeedUtil {
    int height = 340;// dp

    private boolean isAlive = true;// 是否处于生命周期可见 状态
    private String TAG = "GMUtil";

    private static volatile GMFeedUtil singleton = null;

    private GMFeedUtil() {
    }

    public static GMFeedUtil getInstance() {
        if (singleton == null) {
            synchronized (GMFeedUtil.class) {
                if (singleton == null) {
                    singleton = new GMFeedUtil();
                }
            }
        }
        return singleton;
    }


    ////////////////////////////////////////////////////


    public String mMediaId = ""; // 融合广告位

    private TTFeedAd mTTFeedAd; // Feed广告对象

    private TTAdNative.FeedAdListener mFeedAdListener; // 广告加载监听器
    private MediationExpressRenderListener mExpressAdInteractionListener; // 模板广告展示监听器

    private TTNativeAd.AdInteractionListener mAdInteractionListener; // 自渲染广告展示监听器

    private FrameLayout mFeedContainer;


    AppCompatActivity activity;
    ValueCallback<Boolean> valueCallback;

    public void loadFeed(@NonNull AppCompatActivity activity,
                         @NonNull FrameLayout container,
                         @NonNull ValueCallback<Boolean> valueCallback
    ) {

        this.mMediaId = CodeRewardUtil.getInstance().getAdId(HYLC_XXL_INFOSTREAM_TEST, HYLC_XXL_INFOSTREAM_TEST_INDEX);
        Log.i(TAG, "feed gm ad id: " + this.mMediaId);

        this.activity = activity;
        this.valueCallback = valueCallback;
        this.mFeedContainer = container;

        addLifecycle();
        initListeners();


        loadFeedAd();

    }

    private void callbackSuccess() {
        if (this.valueCallback == null) return;
        this.valueCallback.onReceiveValue(true);
    }

    private void callbackFail() {
        if (this.valueCallback == null) return;
        this.valueCallback.onReceiveValue(false);
    }

    private void addLifecycle() {// 重要
        if (this.activity == null) return;

        this.activity.getLifecycle().addObserver(new DefaultLifecycleObserver() {
            // 还有很多生命周期都可以感知
            // 这里只关注 onDestroy()的注销ad对象
            @Override
            public void onDestroy(LifecycleOwner owner) {
                DefaultLifecycleObserver.super.onDestroy(owner);
//                Logger.d("===========LifecycleOwner=========onDestroy===========");

                /** 6、在onDestroy中销毁广告 */
                if (mTTFeedAd != null) {
                    mTTFeedAd.destroy();
                }

                isAlive = false;

            }

            @Override
            public void onResume(LifecycleOwner owner) {
                DefaultLifecycleObserver.super.onResume(owner);
                isAlive = true;
            }

            @Override
            public void onPause(LifecycleOwner owner) {
                DefaultLifecycleObserver.super.onPause(owner);
                isAlive = false;
            }
        });
    }

    private void loadFeedAd() {

        float w = UIUtils.px2dip(this.activity, UIUtils.getScreenWidthInPx(this.activity)) * 0.9f;

        /** 1、创建AdSlot对象 */

        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(this.mMediaId)
//                .setImageAcceptedSize(
//                        UIUtils.getScreenWidthInPx(this.activity),
//                        UIUtils.dp2px(this.activity, height)
//                ) // 单位px
                .setExpressViewAcceptedSize(
                        w,
                        w * 0.8f
                )
                .setAdCount(1) // 请求广告数量为1到3条 （优先采用平台配置的数量）
                .build();

        /** 2、创建TTAdNative对象 */

        TTAdNative adNativeLoader = TTAdManagerHolder.get().createAdNative(this.activity);

        /** 3、创建加载、展示监听器 */
        initListeners();

        /** 4、加载广告 */

        adNativeLoader.loadFeedAd(adSlot, mFeedAdListener);
    }

    // 广告加载成功后，展示广告
    private void showFeedAd() {
        if (this.mTTFeedAd == null) {
            Log.i(TAG, "请先加载广告或等待广告加载完毕后再调用show方法");
            return;
        }
        /** 5、展示广告 */
        MediationNativeManager manager = mTTFeedAd.getMediationManager();
        if (manager != null) {
            if (manager.isExpress()) { // --- 模板feed流广告
                mTTFeedAd.setExpressRenderListener(mExpressAdInteractionListener);
                mTTFeedAd.render(); // 调用render方法进行渲染，在onRenderSuccess中展示广告

            } else {                   // --- 自渲染feed流广告

                // 自渲染广告返回的是广告素材，开发者自己将其渲染成view
//                View feedView = FeedAdUtils.getFeedAdFromFeedInfo(mTTFeedAd, this, null, mAdInteractionListener);
//                if (feedView != null) {
//                    UIUtils.removeFromParent(feedView);
//                    mFeedContainer.removeAllViews();
//                    mFeedContainer.addView(feedView);
//                }
            }
        }
    }

    private void initListeners() {
        // 广告加载监听器

        this.mFeedAdListener = new TTAdNative.FeedAdListener() {
            @Override
            public void onError(int i, String s) {
                Log.d(TAG, "feed load fail, errCode: " + i + ", errMsg: " + s);

                callbackFail();
            }

            @Override

            public void onFeedAdLoad(List<TTFeedAd> list) {
                if (list != null && list.size() > 0) {
                    Log.d(TAG, "feed load success");
                    mTTFeedAd = list.get(0);

                    showFeedAd();

                } else {
                    Log.d(TAG, "feed load success, but list is null");
                }
            }
        };
        // 模板广告展示监听器
        this.mExpressAdInteractionListener = new MediationExpressRenderListener() {
            @Override
            public void onRenderFail(View view, String s, int i) {
                Log.d(TAG, "feed express render fail, errCode: " + i + ", errMsg: " + s);
            }

            @Override
            public void onAdClick() {
                Log.d(TAG, "feed express click");
            }

            @Override
            public void onAdShow() {
                Log.d(TAG, "feed express show");
            }

            @Override
            public void onRenderSuccess(View view, float v, float v1, boolean b) {
                Log.d(TAG, "feed express render success");
                if (mTTFeedAd != null) {
                    View expressFeedView = mTTFeedAd.getAdView(); // *** 注意不要使用onRenderSuccess参数中的view ***
                    UIUtils.removeFromParent(expressFeedView);
                    mFeedContainer.removeAllViews();
                    mFeedContainer.addView(expressFeedView);
                }
            }
        };
        // 自渲染广告展示监听器

        this.mAdInteractionListener = new TTNativeAd.AdInteractionListener() {
            @Override

            public void onAdClicked(View view, TTNativeAd ttNativeAd) {
                Log.d(TAG, "feed click");
            }

            @Override

            public void onAdCreativeClick(View view, TTNativeAd ttNativeAd) {
                Log.d(TAG, "feed creative click");
            }

            @Override

            public void onAdShow(TTNativeAd ttNativeAd) {
                Log.d(TAG, "feed show");
            }
        };
    }
}
